package com.boot.controller;

import com.boot.commons.Result;
import com.boot.commons.utils.JwtUtils;
import com.boot.model.User;
import com.boot.model.UserVO;
import com.boot.service.IUserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        log.info("员工登录: {}", user);
        User loginUser = userService.login(user);

        //登录成功,生成令牌,下发令牌
        if (loginUser != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getAdid());
            claims.put("name", loginUser.getAdname());
            claims.put("username", loginUser.getUsername());
            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
            log.info(jwt);
            UserVO userVO = new UserVO();

            userVO.setId(loginUser.getAdid());
            userVO.setName(loginUser.getAdname());
            userVO.setAge(loginUser.getAge());
            userVO.setSex(loginUser.getSex());
            userVO.setBirthday(loginUser.getBirthday());
            userVO.setIdCard(loginUser.getIdCard());
            userVO.setPhone(loginUser.getPhone());
            userVO.setUsername(loginUser.getUsername());
            userVO.setPassword(loginUser.getPassword());

            userVO.setToken(jwt);
            return Result.success(userVO);
        }
        //登录失败, 返回错误信息
        return Result.error("登录失败");


    }

}